﻿using B.S.Base.Read.API.Application.Command;
using B.S.Base.Read.API.Dto;
using B.S.Base.Read.API.Application.Command;
using MediatR;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Read.API.Application.CommandHandLer
{
    public class UserPermissionCommandHandLer : IRequestHandler<UserPermissionCommand, APIResult<List<Rolepermission>>>
    {
        private readonly IBaseRepostiy<MenuRoleModel> permission;
        private readonly IBaseRepostiy<MenuModel> menu;

        public UserPermissionCommandHandLer(IBaseRepostiy<MenuRoleModel> permission, IBaseRepostiy<MenuModel> menu)
        {
            this.permission = permission;
            this.menu = menu;
        }

        public Task<APIResult<List<Rolepermission>>> Handle(UserPermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<Rolepermission>> result = new APIResult<List<Rolepermission>>();

            result.Code = ResultCode.Ok;
            result.Message = "成功";
            var list = request.Rid.Split(',').ToList();
            var menus = permission.GetAll();
            List<int> model = new List<int>();
            foreach (var item in list)
            {
                var mids = menus.Where(x => x.Rid == Convert.ToInt32(item)).Select(x => x.Mid).ToList();
                model.AddRange(mids);
            }
            var menusQuery = menu.GetAll().Where(x => !x.IsDeleted);
            var data = find(0, menusQuery.ToList(), model);
            result.Data = data;      
            return Task.FromResult(result);
        }
        public List<Rolepermission> find(int id, List<MenuModel> ids, List<int> mid)
        {
            var res = ids.Where(x => x.Pid == id && mid.Contains(x.Id)).ToList();
            List<Rolepermission> list = new List<Rolepermission>();
            foreach (var item in res)
            {
                list.Add(new Rolepermission()
                {
                    Url = item.Url,
                    MenuName = item.MenuName,
                    Children = find(item.Id, ids, mid)
                });
            }
            return list;
        }
    }
}
